package lvm

import (
	"bufio"
	"context"
	"github.com/sirupsen/logrus"
	"strings"
)

// VGList 存储池列表
func VGList(ctx context.Context) (map[string]*VolumeGroup, error) {
	result, err := execCommand(ctx, "vgs",
		"-o", "vg_name,vg_exported,vg_size,vg_free,vg_uuid",
		"--noheadings", "--units", "B", "--separator", "||")
	if err != nil {
		return nil, err
	}
	logrus.Debugf("vglist: %v", result)
	return processVGList(result)
}

// yctc||||30974935040B||9500098560B||U9XA5c-hCID-h1PZ-g57k-7KDb-chRy-gdCjQC
func processVGList(result string) (vgs map[string]*VolumeGroup, err error) {
	scanner := bufio.NewScanner(strings.NewReader(result))
	vgs = make(map[string]*VolumeGroup)
	for scanner.Scan() {
		l := strings.TrimSpace(scanner.Text())
		sps := strings.Split(l, "||")
		if len(sps) < 5 {
			continue
		}
		vg := &VolumeGroup{
			Name:     sps[0],
			Exported: false,
			Size:     parseSize(sps[2]),
			FreeSize: parseSize(sps[3]),
			UUID:     sps[4],
		}
		if strings.TrimSpace(sps[1]) == "exported" {
			vg.Exported = true
		}
		vgs[vg.Name] = vg
	}
	if len(vgs) == 0 {
		err = ErrEmpty
	}
	return
}
